<?php
/*
  function: 订单模型

  create by: 徐闻洁
  create date: 2016.12.19
  description:

  modification 0.0.3
  modified by:
  description:
 * 2016/12/26 修改getRefundList,增加分页
 * 2016/2/24  获取配置文件用getConfig();
 * 2017/4/21  添加getOrderidByUserid方法
 * 2017/4/24  getInfo去掉timestr;
 * 2017/5/2  cancel操作加入action;
 */
namespace app\common\model;

use think\Db;
use think\Model;

class Order extends Model {

    var $userId;
    var $unit_id;
    function __construct() {
        //获取user_id
        if (is_null($this->userId)) {
            $userId = $this->userId = model('user')->getUserId();
        } else {
            $userId = $this->userId;
        }
        if (!$userId) {
            return;
        }
    }
    function unit($unit_id){
        if(!$unit_id){
            $this->unit_id = 0;
            return;
        }
        $this->unit_id = $unit_id;
    }
    //根据class_id获取class数据
    private function getProductClass($class) {
        $config=getConfig('product');
        foreach ($config as $k => $v) {
            if (is_numeric($class)) {
                if ($v['id'] == $class) {
                    $classInfo = $k;
                    return $classInfo;
                }
            } else {
                if ($k == $class) {
                    $classInfo = $v['id'];
                    return $classInfo;
                }
            }
        }
    }

    //生成订单
    //demand订单产品类型
    //data订单数据
    function add($demand, $data,$cafe_coupon=0) {
        //权限判断
//        if (!model('admin')->is($demand)['state']) {
//            return array('state' => 0, 'errormsg' => 'authority incorrect');
//        }
        if (!$demand) {
            return array('state' => 0, 'errormsg' => 'need demand');
        }
        if (!$data) {
            return array('state' => 0, 'errormsg' => 'need data');
        }
        $data['total_fee'] = (int) $data['total_fee'];
        if(isset($data['total_fee_original'])){
            $data['total_fee_original'] = (int) $data['total_fee_original'];
        }
        if(!$cafe_coupon){
            if ($data['total_fee'] == 0 || !$data['total_fee']) {
                return array('state' => 0, 'errormsg' => 'total_fee error');
            }
        }
        if($this->unit_id){
            $data['unit_id'] = $this->unit_id;
        }
        $config = getConfig("product");
        $data['class'] = $config[$demand]['id'];
        $ret = db('order')->insertGetId($data);
        if (!$ret) {
            return array('state' => 0, 'errormsg' => 'create_order error');
        }
        return array('state' => 1, 'errormsg' => 'ok', 'data' => array('info' => array('order_id' => $ret)));
    }

    //删除订单
    function cancel($order_id) {
        if (!$order_id) {
            return array('state' => 0, 'errormsg' => 'data error');
        }
//        $where = "order_id in($order_id)";
//        if($this->unit_id){
//            $where .= " and unit_id = $this->unit_id";
//        }
//        $order_info = db('order')->where($where)->find();
//        //检查订单查询结果,状态,订单生成者
//        if (!$order_info || $order_info['state'] != 1 || ($this->userId != $order_info['user_id'])) {
//            return array('state' => 0, 'errormsg' => 'order error');
//        }
        //判断是否未支付
        $data['state'] = '0';
        $order_id = explode(',',$order_id);
        foreach ($order_id as $k =>$v) {
            $pay = db('pay')->where("order_id =$v")->find();
            if(!$pay){
                $ret = db('order')->where("order_id = $v")->update($data);
            }else{
                $orderid[] = $v;
            }
        }
        if(isset($orderid)&&isset($ret)){
            $id = implode(',',$orderid);
            return array('state'=>1,'errormsg'=>'删除成功!其中已支付订单'.$id.'不能删除!');
        }
        if(isset($order_id)&& !isset($ret)){
            $id = implode(',',$orderid);
            return array('state'=>0,'errormsg'=>'删除失败,已支付订单'.$id.'不能删除!');
        }
        if(!isset($order_id) && isset($ret)){
            return array('state'=>1,'errormsg'=>'删除成功!');
        }
        model('action')->add('order_cancel','order_id',$order_id);
        return array('state' => 1, 'errormsg' => 'ok');
    }

    //获取订单列表
    function getListToday($filter,$demand,$unpaid=false,$channel) {
        //权限判断
//        if (!model('admin')->is($demand)['state']) {
//            return array('state' => 0, 'errormsg' => 'authority incorrect');
//        }
        if (!$demand) {
            return array('state' => 0, 'errormsg' => 'need demand');
        }
        $user_ids = '';
        $admin_ids = '';
        $class = getConfig('product')[$demand]['id'];
        $where="o.class = $class and state = 1";
        $where_b = "";
        $where_c = "";
        if($this->unit_id){
            $where .= " and o.unit_id = $this->unit_id";
            $where_b .= " and unit_id = $this->unit_id";
            $where_c .= " and unit_id = $this->unit_id";
        }
        $order = 'o.create_time desc';
        if (isset($filter['page'])&&$filter['page'] != '') {
            $pages = $filter['page'] - 1;
        } else {
            $pages = 0;
        }
        if (isset($filter['maxPerPage'])&&$filter['maxPerPage'] != '') {
            $maxPerPage = $filter['maxPerPage'];
        } else {
            $maxPerPage = 12;
        }
        if(isset($filter['keywords'])&& $filter['keywords']!=""){
            $user = model('user')->exist(['tel'=>$filter['keywords']]);
            if($user['state']){
                $user_ids = $admin_ids = $user['data']['user_id'];
                $where .= " and o.user_id=$user_ids";
                $where_b = "user_id=$user_ids";
                $where_c = "user_id=$user_ids";
            }else{
                $card = model('card')->getUserIdByCode($filter['keywords']);
                if($card['state']){
                    $user_ids = $admin_ids = $card['data']['user_id'];
                    $where .= " and o.user_id=$user_ids";
                    $where_b = "user_id=$user_ids";
                    $where_c = "user_id=$user_ids";
                }else{
                    if(is_numeric($filter['keywords'])){
                        $where .= " and o.order_id=".$filter['keywords'];
                        $where_b = "order_id=".$filter['keywords'];
                        $where_c = "order_id=".$filter['keywords'];
                    }else{
                        $user_wh = keywordSQL($filter['keywords'],'set_name,nickname,real_name');
                        $user = Db::name('user')->where($user_wh)->select();
                        if (!$user){
                            return ['state'=>0,'errormsg'=> 'user notfind'];
                        }$ids = '';
                        foreach ($user as $k=>$v){
                            $ids .= $v['user_id'].',';
                        }
                        $ids = substr($ids,0,-1);
                        $where .= " and o.user_id in ($ids)";
                        $where_b .= "user_id in ($ids)";
                        $where_c .= "user_id in ($ids)";
                    }
                }
            }
        }
        if($channel){
            switch ($channel) {
                case "cashpay":
                    $where .= " and p.channel = 1";
                    $where_c .= " and p.channel = 1";
                    break;
                case "accountpay":
                    $where .= " and p.channel = 2";
                    $where_c .= " and p.channel = 2";
                    break;
                case "wxpay":
                    $where .= " and p.channel = 101";
                    $where_c .= " and p.channel = 101";
                    break;
                case "alipay":
                    $where .= " and p.channel = 201";
                    $where_c .= " and p.channel = 201";
                    break;
                case "unionpay":
                    $where .= " and p.channel = 3";
                    $where_c .= " and p.channel = 3";
                    break;
            }
        }
        if (isset($filter['order'])&&$filter['order']){
            $order = 'b.create_time asc';
        }
        //当前时间区间
        $date = strtotime(date('Ymd')); //今天0点开始时间
        $time = strtotime(date('Ymd')) + 86400; //今天24点结束时间
        $class = $this->getProductClass($demand);
        $prefix=config('database.prefix');
        $field = "o.order_id,o.detail,o.user_id,o.class,o.state,o.admin_user_id,o.total_fee,o.create_time,p.pay_id,p.channel,p.method,o.total_fee_original";
        $order_info = db('order')
            ->alias('o')
            ->join($prefix."pay p", 'p.order_id = o.order_id','LEFT')
//            ->field('order_id,detail,create_time,user_id,class,state,admin_user_id,total_fee,total_fee_original')
            ->field($field)
//            ->where("$where and o.order_id in(select order_id from wy_pay)")
            ->where("$where or (o.total_fee = 0 and o.total_fee_original =0 and o.order_id not in(select order_id from ". $prefix."pay))")
            ->limit($pages*$maxPerPage,$maxPerPage)
            ->order($order)
            ->select();
        if($unpaid==true){
//            $order_info = Db::name('order')
//                ->where('class',$class)
//                ->where("not exists(select * from ".$prefix."pay where order_id = ".$prefix."order.order_id)")
//                ->where($where_b)
//                ->limit($pages*$maxPerPage,$maxPerPage)
//                ->order('create_time desc')
//                ->select();
            $order_info = db('order')
                ->alias('o')
                ->join($prefix."pay p", 'p.order_id = o.order_id','LEFT')
//            ->field('order_id,detail,create_time,user_id,class,state,admin_user_id,total_fee,total_fee_original')
                ->field($field)
                ->where($where)
                ->where("o.total_fee != 0 and o.total_fee_original !=0 and o.order_id not in(select order_id from ".$prefix."pay)")
                ->limit($pages*$maxPerPage,$maxPerPage)
                ->order($order)
                ->select();
        }
        foreach ($order_info as $k => $v) {
            $order_info[$k]['class'] = $demand;
        }
        //判断是否有下一页
        $pages = $pages + 1;
//        $type_brand_b = db('pay')->alias('p')->join($prefix."order o", 'p.order_id = o.order_id','LEFT')
//                        ->where($where)->limit($pages * $maxPerPage, $maxPerPage)
//                        ->where('o.total_fee = 0 and o.total_fee_original = 0')
//                        ->order("o.create_time desc")->select();
        $type_brand_b = db('order')
            ->alias('o')
            ->join($prefix."pay p", 'p.order_id = o.order_id','LEFT')
//            ->field('order_id,detail,create_time,user_id,class,state,admin_user_id,total_fee,total_fee_original')
            ->field($field)
            ->where("$where and o.order_id in(select order_id from ".$prefix."pay)")
            ->whereOr("$where and o.total_fee = 0 and o.total_fee_original =0 and o.order_id not in(select order_id from ".$prefix."pay)")
            ->limit($pages*$maxPerPage,$maxPerPage)
            ->order($order)
            ->select();
        if (count($type_brand_b)) {
            $more = 1;
        } else {
            $more = 0;
        }
        return array('state' => 1, 'data' => array('list' => $order_info, 'more' => $more));
    }
    //获取用户订单列表
    function getListForMine($filter,$unpaid=false,$channel) {
        //权限判断
        if (!$this->userId) {
            return array('state' => 0, 'errormsg' => 'authority incorrect');
        }
        $where="state = 1 and o.user_id = $this->userId";
        $where_b = '';
        if($this->unit_id){
            $where .= " and o.unit_id = $this->unit_id";
        }
        $order = 'o.create_time desc';
        if (isset($filter['page'])&&$filter['page'] != '') {
            $pages = $filter['page'] - 1;
        } else {
            $pages = 0;
        }
        if (isset($filter['maxPerPage'])&&$filter['maxPerPage'] != '') {
            $maxPerPage = $filter['maxPerPage'];
        } else {
            $maxPerPage = 12;
        }
        if(isset($filter['keywords'])&& $filter['keywords']!=""){
            if(is_numeric($filter['keywords'])){
                $where .= " and o.order_id=".$filter['keywords'];
                $where_b = "order_id=".$filter['keywords'];
            }
        }
        if($channel){
            switch ($channel) {
                case "cashpay":
                    $where .= " and p.channel = 1";
                    break;
                case "accountpay":
                    $where .= " and p.channel = 2";
                    break;
                case "wxpay":
                    $where .= " and p.channel = 101";
                    break;
                case "alipay":
                    $where .= " and p.channel = 201";
                    break;
                case "unionpay":
                    $where .=" and p.channel = 3";
            }
        }
        if (isset($filter['order'])&&$filter['order']){
            $order = 'b.create_time asc';
        }
        //当前时间区间
        $date = strtotime(date('Ymd')); //今天0点开始时间
        $time = strtotime(date('Ymd')) + 86400; //今天24点结束时间
        $prefix=config('database.prefix');
        $field = "p.order_id,o.detail,o.user_id,o.class,o.state,o.admin_user_id,p.total_fee,p.create_time,p.pay_id,p.channel,p.method,o.total_fee_original";
        $order_info = db('order')->alias('o')
            ->join($prefix."pay p", 'p.order_id = o.order_id')
            ->field($field)->where($where)
            ->limit($pages*$maxPerPage,$maxPerPage)
            ->order($order)->select();
        if($unpaid==true){
            $order_info = Db::name('order')
                ->where("not exists(select * from ".$prefix."pay where order_id = ".$prefix."order.order_id)")
                ->where($where_b)
                ->limit($pages*$maxPerPage,$maxPerPage)
                ->order('create_time desc')
                ->select();
        }
        foreach ($order_info as $k => $v) {
            $demand = $this->getProductClass($v['class']);
            $order_info[$k]['class'] = $demand;
        }
        //判断是否有下一页
        $pages = $pages + 1;
        $type_brand_b = db('order')->alias('o')->join($prefix."pay p", 'p.order_id = o.order_id')
            ->where($where)->limit($pages * $maxPerPage, $maxPerPage)
            ->order("o.create_time desc")->select();
        if (count($type_brand_b)) {
            $more = 1;
        } else {
            $more = 0;
        }
        return array('state' => 1, 'data' => array('list' => $order_info, 'more' => $more));
    }
    //根据user_id获取order_id
    public function getOrderidByUserid($filter)
    {
        if(!$this->userId && !isset($filter['user_id'])){
            return ['state'=>0,'not user exist'];
        }
        $userId = $this->userId;
        if(isset($filter['user_id'])){
            $userId = $filter['user_id'];
        }
        if (isset($filter['page']) && $filter['page'] != '') {
            $pages = $filter['page'] - 1;
        } else {
            $pages = 0;
        }
        if (isset($filter['maxPerPage']) && $filter['maxPerPage'] != '') {
            $maxPerPage = $filter['maxPerPage'];
        } else {
            $maxPerPage = 12;
        }
        $order =Db::name('order')
            ->where("state = 1 and user_id=".$userId)
            ->order('create_time desc')
            ->field('order_id')
            ->limit($pages*$maxPerPage,$maxPerPage)
            ->select();
        $order_id = '';
        foreach ($order as $k =>$v){
            $order_id .= $v['order_id'].',';
        }
        $order_id = rtrim($order_id,',');
        if(empty($order)){
            return array('state'=>1,'data'=>array('list'=>[]));
        }
        $pages = $pages+1;
//        $pages = 4+1;
        $order2 =Db::name('order')
            ->where("state = 1 and user_id=".$userId)
            ->order('create_time desc')
            ->field('order_id')
            ->limit($pages*$maxPerPage,$maxPerPage)
            ->select();
        if(count($order2)){
            $more = 1;
        }else{
            $more = 0;
        }
        return array('state'=>1,'data'=>array('list'=>$order_id,'more'=>$more));
    }
    //获取某个单位订单列表
    function getListForUnit($demand, $filter) {
        
    }

    //获取某个订单的详细信息
    function getInfo($order_id) {
        //判断order_id是否接到
        if (!$order_id) {
            return array('state' => 0, 'errormsg' => 'need order_id');
        }
//        if (!D(Admin)->is(client)[state]) {
//            return array('state' => 0, 'errormsg' => 'authority incorrect');
//        }
        $where = "order_id = '$order_id'";
        if($this->unit_id){
            $where .= " and unit_id = $this->unit_id";
        }
        $orderinfo = db('order')->where($where)->find();
        //判断是否存在或已删除
        if (!$orderinfo || $orderinfo['state'] == 0) {
            return array('state' => 0, 'errormsg' => 'order_id no exist');
        }
        $config =getConfig('product');
        //获取class
        $classinfo = $this->getProductClass($orderinfo['class']);
        $orderInfo['user_id'] = $orderinfo['user_id'];
        $orderInfo['admin_user_id'] = $orderinfo['admin_user_id'];
        $orderInfo['detail'] = $orderinfo['detail'];
        $orderInfo['order_id'] = $orderinfo['order_id'];
        $orderInfo['class'] = $classinfo;
        $orderInfo['time'] = $orderinfo['create_time'];
        $orderInfo['create_time'] = $orderinfo['create_time'];
        $orderInfo['total_fee'] = $orderinfo['total_fee'];
        $orderInfo['total_fee_original'] = $orderinfo['total_fee_original'];
        $orderInfo['refund_in'] = $config[$classinfo]['refund_in'];
        $orderInfo['pay_in'] = $config[$classinfo]['pay_in'];
        return array('data' => array('info' => $orderInfo), 'state' => 1);
    }

    //检查订单支付情况
    function paid($order_id) {
        
    }

    //订单发货
    function send($order_id) {
        
    }

    //订单评论
    function comment($order_id) {
        
    }

    //退款清单
    function getRefundList($demand,$filter,$channel) {
        if (!$demand) {
            return array('state' => 0, 'errormsg' => 'need demand');
        }
//        //权限判断
//        if (!model('admin')->is($demand)['state']) {
//            return array('state' => 0, 'errormsg' => 'authority incorrect');
//        }
        $user_ids = '';
        $admin_ids = '';
        $class = getConfig('product')[$demand]['id'];
        $where="o.class = $class and state = 1";
        if($this->unit_id){
            $where .= " and o.unit_id = $this->unit_id";
        }
        $order = 'o.create_time desc';
        if (isset($filter['page'])&&$filter['page'] != '') {
            $pages = $filter['page'] - 1;
        } else {
            $pages = 0;
        }
        if (isset($filter['maxPerPage'])&&$filter['maxPerPage'] != '') {
            $maxPerPage = $filter['maxPerPage'];
        } else {
            $maxPerPage = 12;
        }
        if(isset($filter['keywords'])&& $filter['keywords']!=""){
            $user = model('user')->exist(['tel'=>$filter['keywords']]);
            if($user['state']){
                $user_ids = $admin_ids = $user['data']['user_id'];
                $where .= " and o.user_id=$user_ids";
            }else{
                $card = model('card')->getUserIdByCode($filter['keywords']);
                if($card['state']){
                    $user_ids = $admin_ids = $card['data']['user_id'];
                    $where .= " and o.user_id=$user_ids";
                }else{
                    if(is_numeric($filter['keywords'])){
                        $where .= " and o.order_id=".$filter['keywords'];
                    }else{
                        $user_wh = keywordSQL($filter['keywords'],'set_name,nickname,real_name');
                        $user = Db::name('user')->where($user_wh)->select();
                        if (!$user){
                            return ['state'=>0,'errormsg'=> 'user notfind'];
                        }$ids = '';
                        foreach ($user as $k=>$v){
                            $ids .= $v['user_id'].',';
                        }
                        $ids = substr($ids,0,-1);
                        $where .= " and o.user_id in ($ids)";
                    }
                }
            }
        }
        if($channel){
            switch ($channel) {
                case "cashpay":
                    $where .= " and p.channel = 1";
                    break;
                case "accountpay":
                    $where .= " and p.channel = 2";
                    break;
                case "wxpay":
                    $where .= " and p.channel = 101";
                    break;
                case "alipay":
                    $where .= " and p.channel = 201";

            }
        }
        if (isset($filter['order'])&&$filter['order']){
            $order = 'b.create_time asc';
        }
        $prefix=config('database.prefix');
        $field = array('r.pay_refund_id','o.order_id','r.refund_fee','r.create_time','r.admin_user_id','o.detail','o.class','o.state','o.user_id','o.receive_id','o.unit_id','p.pay_id','p.channel','p.method');
        //退款订单类型
        //获取product_class配置文件
        if(isset($filter['keywords'])&& $filter['keywords']!=""){
            $user = model('user')->exist(['tel'=>$filter['keywords']]);
            if($user['state']){
                $user_ids = $admin_ids = $user['data']['user_id'];
                $where .= " and o.user_id=$user_ids or o.admin_user_id=$admin_ids";
            }else{
                if(is_numeric($filter['keywords'])){
                    $card = model('card')->getUserIdByCode($filter['keywords']);
                    if($card['state']){
                        $where .= " and o.user_id=".$card['data']['user_id'];
                    }else {
                        $where .= " and o.order_id like " . $filter['keywords'];
                    }
                }else{
                    $name = keywordSQL($filter['keywords'],'nickname,set_name,real_name');
                    $userid = db('user')->field('user_id')->where($name)->select();
                    if(!$userid){
                        return array('state'=>0,'errormsg'=>'user not find');
                    }
                    $ids = '';
                    foreach($userid as $k =>$v){
                        $ids .= $v['user_id'].',';
                    }
                    $ids = rtrim($ids,',');
                    $where .=" and o.user_id in ($ids) ";
                }
            }
        }
        if($channel){
            switch ($channel) {
                case "cashpay":
                    $where .= " and p.channel = 1";
                    break;
                case "accountpay":
                    $where .= " and p.channel = 2";
                    break;
                case "wxpay":
                    $where .= " and p.channel = 101";
                    break;
                case "alipay":
                    $where .= " and p.channel = 201";
                    break;
                case "unionpay":
                    $where .= " and p.channel = 3";
            }
        }

//        $refund = db('pay_refund')->alias('r')->field($field)
//            ->join($prefix."order o",'o.order_id = r.order_id')
//            ->join($prefix."pay p","p.order_id = r.order_id")->where($where)->order($order)
//            ->limit($pages * $maxPerPage, $maxPerPage)
//            ->order("r.create_time desc")->select();
        $list = db('pay_refund')->alias('r')->field($field)
            ->join($prefix."order o",'o.order_id = r.order_id')
            ->join($prefix."pay p","p.order_id = r.order_id")
            ->where($where)
            ->order($order)
            ->order("r.create_time desc")
            ->paginate(12,false,['page'=>$pages]);
        $page = $list->render();
        $list = $list->items();
        $page=preg_replace("(<a[^>]*page[=|/](\d+).+?>(.+?)<\/a>)","<a href='javascript:ajax_page($1);'>$2</a>",$page);
        $page=str_replace("&laquo;","上一页",$page);
        $page=str_replace("&raquo;","下一页",$page);
        return array('state' => 1,'data' => array('list' => $list),'page'=>$page);
    }
    
    //汇总表
    
}
